/*
* Copyright (c)  2017, ueboot.com
* All rights reserved.
* 2017-11-05 17:53:32
*/
package com.ueboot.weishop.admin.controller.order;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ueboot.core.exception.BusinessException;
import com.ueboot.core.http.response.Response;
import com.ueboot.core.utils.DateUtils;
import com.ueboot.weishop.admin.controller.order.vo.*;
import com.ueboot.weishop.entity.order.OrderEntity;
import com.ueboot.weishop.entity.order.OrderEnum;
import com.ueboot.weishop.entity.order.OrderIssueEntity;
import com.ueboot.weishop.service.order.OrderIssueNewService;
import com.ueboot.weishop.service.order.OrderIssueService;
import com.ueboot.weishop.service.order.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by ziv  on 2017-11-05 17:53:32.
 *
 * @author ziv
 * @since 2.0 by autocode
 */
@Slf4j
@RestController
@RequestMapping(value = "/orderIssue")
public class OrderIssueController {

	@Autowired
	private OrderIssueService orderIssueService;

	@Autowired
	private OrderIssueNewService orderIssueNewService;

	@RequiresPermissions("orderIssue:read")
	@RequestMapping(value = "/page", method = RequestMethod.POST)
	public Response<Page<OrderIssueResp>> page(@PageableDefault(value = 15, sort = {"id"}, direction = Sort.Direction.DESC)
			                                           Pageable pageable, @RequestBody(required = false) OrderIssueFindReq request) {
		OrderIssueEntity orderIssue = new OrderIssueEntity();
		BeanUtils.copyProperties(request, orderIssue);

		Page<OrderIssueEntity> entities = orderIssueNewService.pagingSearch(pageable, orderIssue, request.getLastSendDmsTimeStart(), request.getLastSendDmsTimeEnd());
		Page<OrderIssueResp> body = entities.map(entity -> {
			OrderIssueResp resp = new OrderIssueResp();
			BeanUtils.copyProperties(entity, resp);
			if (null != entity.getLastSendDmsTime()) {
				resp.setLastSendDmsTime(DateUtils.format(entity.getLastSendDmsTime(), DateUtils.FORMAT_DATE_TIME_DEFAULT));
			}
			return resp;
		});

		return new Response<>(body);
	}

	@RequiresPermissions("orderIssue:read")
	@RequestMapping(value = "/find", method = RequestMethod.POST)
	public Response<List<OrderIssueResp>> find(@RequestBody(required = false) OrderIssueFindReq request) {

		OrderIssueEntity orderIssue = new OrderIssueEntity();
		BeanUtils.copyProperties(request, orderIssue);
		List<OrderIssueEntity> entities = orderIssueNewService.findSearch(orderIssue, request.getLastSendDmsTimeStart(), request.getLastSendDmsTimeEnd());

		List<OrderIssueResp> bodyResp = Lists.newLinkedList();
		entities.forEach(entity -> {
			OrderIssueResp resp = new OrderIssueResp();
			BeanUtils.copyProperties(entity, resp);
			if (null != entity.getLastSendDmsTime()) {
				resp.setLastSendDmsTime(DateUtils.format(entity.getLastSendDmsTime(), DateUtils.FORMAT_DATE_TIME_DEFAULT));
			}
			bodyResp.add(resp);
		});
		return new Response<>(bodyResp);
	}


	/*下发DMS*/
	@RequiresPermissions("orderIssue:senddown")
	@RequestMapping(value = "/savesenddown", method = RequestMethod.POST)
	public Response<Map<String, String>> savesenddown(@RequestBody OrderIssueReq req) {
		String code = "";
		String message = "";
		try {
			//查询历史发送DMS订单信息
			OrderIssueEntity orderIssue = orderIssueService.get(req.getId());
			if (orderIssue == null) {
				throw new BusinessException("01", "未找到订单号【" + req.getSeqNo() + "】代金券回传DMS数据");
			}
			List<Map<String, String>> reqList = Lists.newLinkedList();
			Map<String, String> reqMap = Maps.newHashMap();
			reqMap.put("SEQ_NO", orderIssue.getSeqNo());
			reqMap.put("NAME", orderIssue.getName());
			reqMap.put("VIN", orderIssue.getVin());
			reqMap.put("CAMPAIGN_CODE", orderIssue.getCampaignCode());
			reqMap.put("VALID_BEGIN_DATE", orderIssue.getValidBeginDate());
			reqMap.put("VALID_END_DATE", orderIssue.getValidEndDate());
			reqMap.put("TARGET_DEALER", orderIssue.getTargetDealer());
			reqMap.put("USE_DEALER", "");
			reqMap.put("AMOUNT", orderIssue.getAmount());
			reqMap.put("USE_AMOUNT", "0.0");
			reqMap.put("LOWEST_AMOUNT", "0.0");
			reqMap.put("LIMIT_DEDUCT", orderIssue.getLimitDeduct());
			reqMap.put("IS_CANCEL", OrderIssueEntity.CANCER_0);
			reqList.add(reqMap);
			String responseMessage = orderIssueService.sendDmsCoupon(reqList);
			Map dmsResp = JSON.parseObject(responseMessage, Map.class);
			orderIssue.setDmsResult("失败");//默认设置为DMS请求失败
			orderIssue.setCancel(OrderIssueEntity.CANCER_0);//设置请求DMS的取消操作类型，1：自动取消代金券
			Date sendDmsTime = new Date();
			orderIssue.setLastSendDmsTime(sendDmsTime);
			if ("0".equals(dmsResp.get("status_code"))) {
				List<Map<String, String>> contentMapList = (List<Map<String, String>>) dmsResp.get("content");
				Integer sendCount = orderIssue.getSendDmsCount();
				if (sendCount == null) {
					sendCount = 0;
				}
				orderIssue.setSendDmsCount(sendCount + 1);
				String sendHistory = orderIssue.getSendDmsHistory();
				if (sendHistory == null) {
					sendHistory = "";
				}
				if (contentMapList == null || contentMapList.size() == 0) {
					sendHistory += "【发送时间：" + DateUtils.format(sendDmsTime, DateUtils.FORMAT_DATE_TIME_DEFAULT) + "，第" + (orderIssue.getSendDmsCount() + 1) + "次发送，Cancer:0,发送结果：发送成功】";
					orderIssue.setDmsResult("发送成功");
					code = "200";
					message = "发送成功";
				} else {
					Map<String, String> contentMap = contentMapList.get(0);
					String dmsResult = contentMap.get("ERROR_MSG");
					orderIssue.setDmsResult(contentMap.get("ERROR_MSG"));
					sendHistory += "【发送时间：" + DateUtils.format(sendDmsTime, DateUtils.FORMAT_DATE_TIME_DEFAULT) + "，第" + (orderIssue.getSendDmsCount() + 1) + "次发送，Cancer:0，DMS反馈：" + dmsResult + "】";
					code = "400";
					message = "【发送失败，DMS反馈：" + dmsResult + "】";
				}
				orderIssue.setSendDmsHistory(sendHistory);
			}
			orderIssueService.save(orderIssue);
		} catch (Exception ex) {
			code = "400";
			message = ex.getMessage();
		}
		Map<String, String> map = Maps.newHashMap();
		map.put("code", code);
		map.put("message", message);
		return new Response<>(map);
	}

	@RequiresPermissions("orderIssue:save")
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public Response<Void> save(@RequestBody OrderIssueReq req) {
		OrderIssueEntity entity = null;
		if (req.getId() == null) {
			entity = new OrderIssueEntity();
		} else {
			entity = orderIssueService.get(req.getId());
		}
		BeanUtils.copyProperties(req, entity);
		orderIssueService.save(entity);
		return new Response<>();
	}

	@RequiresPermissions("orderIssue:delete")
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public Response<Void> delete(Long[] id) {
		orderIssueService.delete(id);
		return new Response<>();
	}

	@RequiresPermissions("orderIssue:read")
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public Response<OrderIssueResp> get(@PathVariable Long id) {
		OrderIssueEntity entity = orderIssueService.get(id);
		OrderIssueResp resp = new OrderIssueResp();
		BeanUtils.copyProperties(entity, resp);
		return new Response<>(resp);
	}

}
